package com.ruoyi.jxxwx.service.impl;

import java.util.List;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import com.ruoyi.jxxwx.mapper.JxxcoderWxuserMapper;
import com.ruoyi.jxxwx.domain.JxxcoderWxuser;
import com.ruoyi.jxxwx.service.IJxxcoderWxuserService;

import javax.annotation.Resource;

/**
 * 微信用户Serv ice业务层处理
 *
 * @author 九消Coder QQ932696181
 * @date 2022-06-26
 */
@Service
public class JxxcoderWxuserServiceImpl implements IJxxcoderWxuserService
{

        @Autowired
        private TokenService tokenService;

        @Resource
        private AuthenticationManager authenticationManager;

        @Autowired
        private RedisCache redisCache;

        @Autowired
        private ISysUserService userService;

        @Autowired
        private ISysConfigService configService;

        /**
         * 登录验证
         *
         * @param username 用户名
         * @param password 密码
         * @return 结果
         */
        public String login(String username, String password)
        {

            // 用户验证
            Authentication authentication = null;
            try
            {
                // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
                authentication = authenticationManager
                        .authenticate(new UsernamePasswordAuthenticationToken(username, password));
            }
            catch (Exception e)
            {
                if (e instanceof BadCredentialsException)
                {
                    AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                    throw new UserPasswordNotMatchException();
                }
                else
                {
                    AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                    throw new ServiceException(e.getMessage());
                }
            }
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            recordLoginInfo(loginUser.getUserId());
            // 生成token
            return tokenService.createToken(loginUser);
        }


        /**
         * 记录登录信息
         *
         * @param userId 用户ID
         */
        public void recordLoginInfo(Long userId)
        {
            SysUser sysUser = new SysUser();
            sysUser.setUserId(userId);
            sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
            sysUser.setLoginDate(DateUtils.getNowDate());
            userService.updateUserProfile(sysUser);
        }


    public SysUser selectUserByOpenId(String openid) {
        return userService.selectUserByOpenId(openid);
    }

    public SysUser selectUserByphonenumber(String phonenumber) {
        return userService.selectUserByphonenumber(phonenumber);
    }

}
